package com.tealer.myapplication

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.os.MessageQueue
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.tealer.myapplication.databinding.ActivityThirdBinding
import java.lang.ref.WeakReference

/**
 *描述
 *@author Created by lipengbo
 *@email 1162947801@qq.com
 *@time Created on 2023/2/18 17:26
 */
class ThridActivity : AppCompatActivity() {

    private lateinit var binding:ActivityThirdBinding
    val tag:String=ThridActivity::class.java.simpleName

    var handler:Handler?=null
    var token:Int=0

    val MESSAGE_TYPE_SYNC = 1
    val MESSAGE_TYPE_ASYN = 2

    var thread:Thread?=null

    var  looper:Looper?=null



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityThirdBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initHandler()
        binding.btnHandlerSendAsync.setOnClickListener{
            sendSyncBarrier()
        }

        binding.btnHandlerRemoveAsync.setOnClickListener{
            removeSyncBarrier()
        }

        binding.btnHandlerSendMessage.setOnClickListener{
            sendSyncMessage()
        }

        binding.btnHandlerSendAsyncMessage.setOnClickListener{
            sendAsynMessage()
        }
    }

    class MyHandler(activity:ThridActivity,looper:Looper):Handler(looper){
        var weakReference:WeakReference<ThridActivity>?=null
        init {
            weakReference=WeakReference<ThridActivity>(activity)
        }
        override fun handleMessage(msg: Message) {
            weakReference?.get()?.let {
                when(msg.what){
                    it.MESSAGE_TYPE_SYNC->{
                        Log.d(it.tag,"收到普通消息")
                    }
                    it.MESSAGE_TYPE_ASYN->{
                        Log.d(it.tag,"收到异步消息")
                    }
                    else -> {}
                }
            }
        }
    }

    fun initHandler(){
        thread=Thread {

         Looper.prepare()
         Log.d(tag,"Looper.myLooper：${Looper.myLooper()}")
         Log.d(tag,"Looper.getMainLooper()：${Looper.getMainLooper()}")
         looper=Looper.myLooper()
         handler=MyHandler(this@ThridActivity,Looper.myLooper()!!)
         Looper.loop()
     }
        thread?.start()

    }

    fun sendSyncBarrier(){
        try {
            Log.d(tag,"插入同步屏障");
            var queue=handler?.looper!!.queue
            var method= MessageQueue::class.java.getDeclaredMethod("postSyncBarrier")
            method.isAccessible=true
            queue?.let {
                token=method.invoke(it) as Int

                Log.d(tag,"插入同步屏障 token=$token");
            }
        }catch (exec:Exception){
            exec.printStackTrace()
        }
    }

    fun removeSyncBarrier(){
        try {
            Log.d(tag,"移除屏障")
            var queue=handler?.looper!!.queue
            var method= MessageQueue::class.java.getDeclaredMethod("removeSyncBarrier",Int::class.java)
            method.isAccessible=true
            queue?.let {
                method.invoke(it,token)
            }
        }catch (exec:Exception){
            exec.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        Log.d(tag,"MyApplication.instance:${MyApplication.instance}")
    }

    //往消息队列插入普通消息
    fun  sendSyncMessage(){
        Log.d(tag,"插入普通消息")
        var message= Message.obtain().apply {
            what=MESSAGE_TYPE_SYNC
        }
        handler?.sendMessageDelayed(message,1000);
    }

    //往消息队列插入异步消息
    fun sendAsynMessage() {
        Log.d(tag,"插入异步消息")
        var message= Message.obtain().apply {
            what=MESSAGE_TYPE_ASYN
            isAsynchronous=true
        }
        handler?.sendMessageDelayed(message,1000);
    }


    override fun onStop() {
        super.onStop()
        Log.d(tag,"onStop")
        looper?.let {
            it.quit()
        }
    }


}